package com.fare.taluo.application.impl.crawl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dayatang.domain.InstanceFactory;
import com.dayatang.querychannel.service.QueryChannelService;
import com.dayatang.querychannel.support.Page;
import com.fare.taluo.GlobalsConst;
import com.fare.taluo.application.crawl.TaskTemplateApplication;
import com.fare.taluo.application.plane.channel.SourceApplication;
import com.fare.taluo.application.plane.city.PortApplication;
import com.fare.taluo.auth.security.LogonUserCertificate;
import com.fare.taluo.core.domain.Convert;
import com.fare.taluo.core.domain.crawl.TaskAssignDayEntity;
import com.fare.taluo.core.domain.crawl.TaskTemplateEntity;
import com.fare.taluo.io.excel.ExcelImportException;
import com.fare.taluo.util.StringUtils;
import com.fare.taluo.vo.auth.UserInfoVO;
import com.fare.taluo.vo.core.PortEntityVO;
import com.fare.taluo.vo.core.SourceEntityVO;
import com.fare.taluo.vo.core.TaskAssignDayEntityVO;
import com.fare.taluo.vo.core.TaskInfoEntityVO;
import com.fare.taluo.vo.core.TaskInfoEntityVOVO;
import com.fare.taluo.vo.crawl.CrawlLineVO;

@Transactional
@Scope("singleton")
@Service("taskInfoApplication")
public class TaskTemplateApplicationImpl implements TaskTemplateApplication {
	
	
	@Resource(name="portApplication")
	private PortApplication portApplication;
	
	@Autowired
	public void setPortApplication(PortApplication portApplication) {
		this.portApplication = portApplication;
	}

	@Resource(name="taskInfoApplication")
	private TaskTemplateApplication taskInfoApplication;
	@Autowired
	public  QueryChannelService queryChannel1;
	@Override
	public TaskInfoEntityVO findTaskInfoEntityVO(long id) throws Exception {
		TaskTemplateEntity task = TaskTemplateEntity.get(TaskTemplateEntity.class, id);
		TaskInfoEntityVO vo  = new TaskInfoEntityVO();
		if(task != null){
			
			vo.setTaskName(task.getName());
			vo.setFrequency(task.getFrequency()/60+"");
			vo.setFromCity(task.getFromCity());
			vo.setGrabChannel(task.getGrabChannel());
			vo.setGrabsopeBegin(task.getGrabScopeBegin());
			vo.setGrabsopeEnd(task.getGrabScopeEnd());
			vo.setFromCityName(task.getFromCityName());
			vo.setToCityName(task.getToCityName());
			vo.setReturnDateScope(task.getReturnDateScope());
			vo.setId(task.getId());
			vo.setRemark(task.getRemark());
			vo.setToCity(task.getToCity());
			vo.setValidityFrom(task.getValidityFrom());
			vo.setValidityTo(task.getValidityTo());
			vo.setUserCreateTime(task.getCreateTime());
			vo.setPriority(task.getPriority());
			vo.setArea(task.getAreaName());
			vo.setAreaCode(task.getAreaCode());
			vo.setGrabChannelId(task.getGrabChannelId());

			if(task.getAssignDayList()!=null){
				List<TaskAssignDayEntityVO> assignDayList =new ArrayList<TaskAssignDayEntityVO>();
				for(TaskAssignDayEntity entity:task.getAssignDayList()){
					TaskAssignDayEntityVO assignVO=new TaskAssignDayEntityVO();
					assignVO.setId(entity.getId());
					assignVO.setAssignFlightDay(entity.getAssignFlightDay());
					assignVO.setAssignRoundDay(entity.getAssignRoundDay());
					assignDayList.add(assignVO);
				}
				vo.setAssignDayList(assignDayList);
			}
			
			vo.setIsReturn(String.valueOf(task.getIsReturn()));
		}
		return vo;
	}

	private void setAssignDayList(List<TaskAssignDayEntity> assignDayList) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void deleteTaskInfoEntity(long id) throws Exception {
		TaskTemplateEntity task = TaskTemplateEntity.get(TaskTemplateEntity.class, id);
		task.remove();
	}

	@Override
	public void saveOrUpdateTaskInfoEntity(String taskName,String grabChannel,String fromCity,String fromCityName,String toCity,String toCityName
			,Date validityFrom,Date validityTo,int grabsopeBegin,int grabsopeEnd,
			String frequency,String remark,String isReturn,int returnDateScope,
			String isEnable,UserInfoVO user,Date userCreateTime,int priority, 
			long taskId, long sourceId,String hbaseKey) throws Exception {
		TaskTemplateEntity taskInfo = new TaskTemplateEntity();

		PortEntityVO portVO = null;
		if(StringUtils.isNotEmpty(fromCity)){
			portVO = portApplication.findCityNameByPortCode(fromCity);
		}
		if(null != portVO && 
				!StringUtils.isEmpty(portVO.getAreaCode()) &&
				!StringUtils.isEmpty(portVO.getAreaName())){
			taskInfo.setAreaName(portVO.getAreaName());
			taskInfo.setAreaCode(portVO.getAreaCode());
		}else{
			throw new Exception("机场区域信息为空");
		}
		taskInfo.setName(taskName);
		taskInfo.setGrabChannel(grabChannel);
		taskInfo.setFromCity(fromCity);
		taskInfo.setFromCityName(fromCityName);
		taskInfo.setToCity(toCity);
		taskInfo.setToCityName(toCityName);
		taskInfo.setValidityFrom(validityFrom);
		taskInfo.setValidityTo(validityTo);
		//从小时转为分钟
		taskInfo.setFrequency(Integer.valueOf(frequency));
		taskInfo.setRemark(remark);
		taskInfo.setGrabScopeBegin(grabsopeBegin);
		taskInfo.setGrabScopeEnd(grabsopeEnd);
		taskInfo.setIsReturn(StringUtils.isNotBlank(isReturn) && NumberUtils.isNumber(isReturn) ? Integer.valueOf(isReturn) : 0);
		taskInfo.setReturnDateScope(returnDateScope);
		taskInfo.setStatus(StringUtils.isNotBlank(isEnable) && NumberUtils.isNumber(isEnable) ? Integer.valueOf(isEnable) : 1);
		taskInfo.setNextGrabTime(new Date());
		taskInfo.setPriority(priority);
		taskInfo.setGrabChannelId(sourceId);
		taskInfo.setAttachHbaseKey(hbaseKey);
		taskInfo.setUserName(user.getUserName());
		taskInfo.setUserId(user.getAccoutId());
		if(taskId>0){taskInfo.setId(taskId);}
		//南航的相应处理
		taskInfo.saveOrUpdateTaskInfoEntity();
	}

	@Override
	public List<TaskInfoEntityVO> findTaskInfoEntityVOCriteriaList(
			String grabChannel, String fromCity, String toCity,int grabsopeBegin,int grabsopeEnd, Date validityFrom,
			int pageNum, int pageSize) {
		TaskTemplateEntity taskInfo = new TaskTemplateEntity();
		List<TaskTemplateEntity> taskInfoList = taskInfo.findTaskInfoEntityCriteriaList(grabChannel, fromCity, toCity, grabsopeBegin,grabsopeEnd,validityFrom, pageNum, pageSize);
		
		List<TaskInfoEntityVO> voList = new ArrayList<TaskInfoEntityVO>();
		if(taskInfoList != null){
			if(taskInfoList.size() > 0){
				for (TaskTemplateEntity task : taskInfoList) {
					TaskInfoEntityVO vo  = new TaskInfoEntityVO();
					vo.setId(task.getId());
					vo.setTaskName(task.getName());
					vo.setFrequency(task.getFrequency()+"");
					vo.setFromCity(task.getFromCity());
					vo.setGrabChannel(task.getGrabChannel());
					vo.setFromCityName(task.getFromCityName());
					vo.setToCityName(task.getToCityName());
					vo.setPriority(task.getPriority());
					//
					
					vo.setIsReturn(task.getIsReturn().toString());
					vo.setReturnDateScope(task.getReturnDateScope());
					vo.setGrabsopeBegin(task.getGrabScopeBegin());
					vo.setGrabsopeEnd(task.getGrabScopeEnd());
					//vo.setGrabsope(task.getGrabsope());
					vo.setRemark(task.getRemark());
					vo.setToCity(task.getToCity());
					vo.setValidityFrom(task.getValidityFrom());
					vo.setValidityTo(task.getValidityTo());
					vo.setUserCreateTime(task.getCreateTime());
					vo.setUserName(task.getUserName());
					vo.setGrabChannelId(task.getGrabChannelId());
					if(task.getAssignDayList()!=null){
						List<TaskAssignDayEntityVO> assignDayList =new ArrayList<TaskAssignDayEntityVO>();
						for(TaskAssignDayEntity entity:task.getAssignDayList()){
							TaskAssignDayEntityVO assignVO=new TaskAssignDayEntityVO();
							assignVO.setId(entity.getId());
							assignVO.setAssignFlightDay(entity.getAssignFlightDay());
							assignVO.setAssignRoundDay(entity.getAssignRoundDay());
							assignDayList.add(assignVO);
						}
						vo.setAssignDayList(assignDayList);
					}
					voList.add(vo);
				}
			}
		}
		return voList;
	}

	@Override
	public int countTaskInfoEntityCriteria(String grabChannel, String fromCity,
			String toCity,Date validityFrom, int grabsopeBegin,int grabsopeEnd) {
		TaskTemplateEntity taskInfo = new TaskTemplateEntity();
		return taskInfo.countTaskInfoEntityCriteria(grabChannel, fromCity, toCity,validityFrom,grabsopeBegin,grabsopeEnd);
	}

	@Override
	public List<TaskInfoEntityVOVO> findTaskInfoByConsdions(String grabChannel,
			String fromCity, String toCity, int grabsopeBegin,int grabsopeEnd) {
		TaskTemplateEntity taskInfo = new TaskTemplateEntity();
		List<TaskTemplateEntity> taskInfoList = taskInfo.findTaskInfoByConsdions(grabChannel, fromCity, toCity, grabsopeBegin,grabsopeEnd);
		
		List<TaskInfoEntityVOVO> voList = new ArrayList<TaskInfoEntityVOVO>();
		if(taskInfoList != null){
			if(taskInfoList.size() > 0){
				for (TaskTemplateEntity task : taskInfoList) {
					TaskInfoEntityVOVO vo  = new TaskInfoEntityVOVO();
					if(task.getNextGrabTime() !=null){
						
						vo.setId(task.getId());
						vo.setTaskName(task.getName());
						vo.setGrabChannel(task.getGrabChannel());
						vo.setNextGrabTime(task.getNextGrabTime());
						vo.setNextGrabTimeStr(com.fare.taluo.util.DateUtils.dateToStr(task.getNextGrabTime(),"YYYY-MM-dd HH:mm:ss"));
	//					vo.setGrabsope(task.getGrabsope());
						vo.setValidityFrom(task.getValidityFrom());
						vo.setValidityTo(task.getValidityTo());
						vo.setFrequency(task.getFrequency());
						vo.setUserNmae(task.getUserName());
						vo.setUserCreateTime(task.getCreateTime());
						voList.add(vo);
					}
				}
			}
		}
		return voList;
	}

	@Override
	public List<TaskInfoEntityVOVO> findTaskInfoByConsdion(String grabChannel,
			String fromCity, String toCity) {
		TaskTemplateEntity taskInfo = new TaskTemplateEntity();
		List<TaskTemplateEntity> taskInfoList = taskInfo.findTaskInfoByConsdion(grabChannel, fromCity, toCity);
		
		List<TaskInfoEntityVOVO> voList = new ArrayList<TaskInfoEntityVOVO>();
		if(taskInfoList != null){
			if(taskInfoList.size() > 0){
				for (TaskTemplateEntity task : taskInfoList) {
					TaskInfoEntityVOVO vo  = new TaskInfoEntityVOVO();
					if(task.getNextGrabTime() !=null){
						
						vo.setId(task.getId());
						vo.setTaskName(task.getName());
						vo.setGrabChannel(task.getGrabChannel());
						vo.setNextGrabTime(task.getNextGrabTime());
						vo.setNextGrabTimeStr(com.fare.taluo.util.DateUtils.dateToStr(task.getNextGrabTime(),"YYYY-MM-dd HH:mm:ss"));
	//					vo.setGrabsope(task.getGrabsope());
						vo.setValidityFrom(task.getValidityFrom());
						vo.setValidityTo(task.getValidityTo());
						vo.setFrequency(task.getFrequency());
						vo.setUserNmae(task.getUserName());
						vo.setUserCreateTime(task.getCreateTime());
						voList.add(vo);
					}
				}
			}
		}
		return voList;
	}
	@Override
	public TaskInfoEntityVO findTaskInfoEntityVo(String grabChannel,
			String fromCity, String toCity, Date validityFrom, Date validityTo,
			int grabsopeBegin, int grabsopeEnd) {
		TaskInfoEntityVO vo=null;
		TaskTemplateEntity entity=
				new TaskTemplateEntity().findTaskInfoEntityVo(grabChannel, 
						fromCity, toCity, validityFrom, validityTo, grabsopeBegin, grabsopeEnd);
		if(entity!=null){
			vo=new TaskInfoEntityVO();
			vo.setTaskName(entity.getName());
			vo.setFrequency(entity.getFrequency()/60+"");
			vo.setFromCity(entity.getFromCity());
			vo.setGrabChannel(entity.getGrabChannel());
			vo.setGrabsopeBegin(entity.getGrabScopeBegin());
			vo.setGrabsopeEnd(entity.getGrabScopeEnd());
			vo.setFromCityName(entity.getFromCityName());
			vo.setToCityName(entity.getToCityName());
			vo.setReturnDateScope(entity.getReturnDateScope());
			vo.setId(entity.getId());
			vo.setRemark(entity.getRemark());
			vo.setToCity(entity.getToCity());
			vo.setValidityFrom(entity.getValidityFrom());
			vo.setValidityTo(entity.getValidityTo());
			vo.setUserCreateTime(entity.getCreateTime());
			vo.setPriority(entity.getPriority());
			vo.setArea(entity.getAreaName());
			vo.setAreaCode(entity.getAreaCode());
			vo.setIsReturn(String.valueOf(entity.getIsReturn()));
			if(entity.getAssignDayList()!=null){
				List<TaskAssignDayEntityVO> assignDayList =new ArrayList<TaskAssignDayEntityVO>();
				for(TaskAssignDayEntity en:entity.getAssignDayList()){
					TaskAssignDayEntityVO assignVO=new TaskAssignDayEntityVO();
					assignVO.setId(en.getId());
					assignVO.setAssignFlightDay(en.getAssignFlightDay());
					assignVO.setAssignRoundDay(en.getAssignRoundDay());
					assignDayList.add(assignVO);
				}
				vo.setAssignDayList(assignDayList);
			}
		}
		return vo;
	}

	private SourceEntityVO getSourceEntityVO(List<SourceEntityVO> sources,String sourceName){
		for(SourceEntityVO vo : sources){
			if(vo.getName().equalsIgnoreCase(sourceName)) return vo;
		}
		return null;
	}
	@Override
	public void importTasks(List<CrawlLineVO> lines) throws ExcelImportException{
		StringBuilder sbuilder = new StringBuilder();
		List<String> errorPort3Code = new ArrayList<String>();
		List<String> errorSourceNames = new ArrayList<String>();	
		if(lines != null && !lines.isEmpty())
		{
			List<SourceEntityVO> sources = InstanceFactory.getInstance(SourceApplication.class).findAllSourceEntity();
			
			List<TaskTemplateEntity> templates = new ArrayList<TaskTemplateEntity>();
			PortEntityVO fromPortVO = null;
			PortEntityVO toPortVO = null;
			SourceEntityVO sourceVO = null;
			for(CrawlLineVO vo : lines){
				//网站名称是否在渠道表中
				sourceVO = this.getSourceEntityVO(sources, vo.getWebSite());
				if(sourceVO == null && !errorSourceNames.contains(vo.getWebSite())){
					errorSourceNames.add(vo.getWebSite());
				}
				//起点城市三字码是否存在于库中
				fromPortVO = portApplication.findCityNameByPortCode(vo.getFromCity());
				if(fromPortVO == null && !errorPort3Code.contains(vo.getFromCity())){
					errorPort3Code.add(vo.getFromCity());
				}
				//终点城市三字码是否存在于库中
				toPortVO = portApplication.findCityNameByPortCode(vo.getToCity());
				if(toPortVO == null && !errorPort3Code.contains(vo.getToCity())){
					errorPort3Code.add(vo.getToCity());
				}
				//有验证不通过的数据，则不用再组装数据，直接返回
				if(errorSourceNames.isEmpty() && errorPort3Code.isEmpty()){
					TaskTemplateEntity entity = new TaskTemplateEntity(fromPortVO.getAreaCode(),fromPortVO.getAreaName(),
							fromPortVO.getPortCode(), fromPortVO.getCityName(), toPortVO.getPortCode(), toPortVO.getCityName()
							, sourceVO.getId(), sourceVO.getName(), sourceVO.getHbaseKey());
					entity.setFrequency(vo.getFrequency());
					entity.setGrabScopeBegin(vo.getGradStartDays());
					entity.setGrabScopeEnd(vo.getGradEndDays());
					entity.setIsReturn(vo.isHasReturn() ? 1 : 0);
					if(vo.isHasReturn()){
						String assDay=vo.getAssignDay();
						String assFriDay=vo.getAssignFrightDay();
						if(assDay!=null&& !"".equalsIgnoreCase(assFriDay) && assFriDay!=null && !"".equalsIgnoreCase(assFriDay)){
							String[] listDays =assDay.split(",");
							String[] listFriDays=assFriDay.split(",");
							if(assDay.indexOf("，")>0){
								listDays =assDay.split("，");
							}
							if(assFriDay.indexOf("，")>0){
								listFriDays=assFriDay.split("，");
							}
							int count = listDays.length<=listFriDays.length? listDays.length:listFriDays.length;
							Set<TaskAssignDayEntity> assignDayList=new HashSet<TaskAssignDayEntity>();
							for(int i=0;i<count;i++){
								TaskAssignDayEntity en =new TaskAssignDayEntity();
								if(!isNumeric(listDays[i]) || !isNumeric(listFriDays[i]))
									continue;
								en.setAssignFlightDay(Integer.parseInt(listDays[i]));
								en.setAssignRoundDay(Integer.parseInt(listFriDays[i]));
								en.setTaskTemplateEntity(entity);
								assignDayList.add(en);
							}
							if(assignDayList!=null && assignDayList.size()>0)
							entity.setAssignDayList(assignDayList);
						}
						
					}
					entity.setNextGrabTime(new Date());
					entity.setPriority(vo.getPriority());
					entity.setReturnDateScope(vo.getReturnDays());
					entity.setValidityFrom(vo.getStartEffectDate());
					entity.setValidityTo(vo.getEndEffectDate());
					entity.setName(entity.getGrabChannel()+
							GlobalsConst.SEPARATOR_UNDERLINE+entity.getFromCityName()+
							GlobalsConst.SEPARATOR_UNDERLINE+entity.getToCityName());
		
					templates.add(entity);
				}
			}
			if(!errorSourceNames.isEmpty()){
				sbuilder.append("不存在以下网站名称:\n").append(StringUtils.compList(errorSourceNames)).append("\n");
			}
			if(!errorPort3Code.isEmpty()){
				sbuilder.append("不存在以下城市三字码:\n").append(StringUtils.compList(errorPort3Code)).append("\n");
			}
			if(sbuilder.length() > 0)
				throw new ExcelImportException(sbuilder.toString());
			//入库
			if(!templates.isEmpty()){
				for(TaskTemplateEntity e : templates){
					//入库前进行重复性检验,存在则不入库
					if( !taskInfoApplication.existTask(e.getFromCity(), e.getToCity(), e.getAttachHbaseKey()) ){
						e.saveOrUpdateTaskInfoEntity();
					}
					
				} 
			}
		}
	}

	@Override
	public boolean existTask(String fromCity, String toCity, String hbaseKey) {
		TaskTemplateEntity entity = new TaskTemplateEntity();
		return entity.existTask(fromCity, toCity, hbaseKey);
	}

	@Override
	public Page<TaskInfoEntityVO> findByPage(String grabChannel,
			String fromCityStr, String toCityStr, int formDate, int toDate,
			Date validityFrom, int pageNum, int pageSize) {
		
		String hql = "from TaskTemplateEntity t where 1=1";
		String condition = "";

		List<Object> list = new ArrayList<Object>();
		List<TaskInfoEntityVO> listVo = new ArrayList<TaskInfoEntityVO>();
		if(StringUtils.isNotEmpty(grabChannel)) {
			condition = condition + " and t.grabChannel = ?";
			list.add(grabChannel);
		}
		if(StringUtils.isNotEmpty(fromCityStr)) {
			condition = condition + " and t.fromCity = ?";
			list.add(fromCityStr);
		}
		if(StringUtils.isNotEmpty(toCityStr)) {
			condition = condition + " and t.toCity = ?";
			list.add(toCityStr);
		}
		if(null != validityFrom) {
			condition = condition + " and t.validityFrom = ?";
			list.add(validityFrom);
		}

//		if (grabsope != 0) {
//			if(StringUtils.isNotEmpty(condition)){
//				condition = condition + " and t.grabsope = ?";
//			}else{
//				condition = condition + " where t.grabsope = ?";
//			}
//			list.add(grabsope);
//		}
		
		if(formDate!=-1){
			condition = condition + " and t.grabScopeBegin = ?";
			list.add(formDate);
		}
		
		if(toDate!=-1){
			condition = condition + " and t.grabScopeEnd = ?";
			list.add(toDate);
		}

		hql = hql + condition + " order by t.createTime desc ";
		System.out.println("----"+hql);
		try{
		
		Page<TaskTemplateEntity> page = queryChannel1.queryPagedResultByPageNo(hql.toString(), list.toArray(), pageNum, pageSize);
		if(page.getTotalCount() > 0){
			for(TaskTemplateEntity entity : page.getResult()){
				listVo.add(Convert.convertTaskInfoEntityToVo(entity));
			}
		}
		int start = (pageNum - 1)*pageSize;
		return new Page<TaskInfoEntityVO>(start, page.getTotalCount(), pageSize, listVo);
		
		
		
		}catch(Exception e){
			System.err.print("sfsdf");
			e.printStackTrace();
		}
		return null;
	
		
	}

	@Override
	public List<TaskInfoEntityVO> findTaskInfoByGrabChannel(String grabChannel) {
		TaskTemplateEntity taskInfo = new TaskTemplateEntity();
		List<TaskTemplateEntity> taskInfoList = taskInfo.findTaskInfoByGrabChannel(grabChannel);
		
		List<TaskInfoEntityVO> voList = new ArrayList<TaskInfoEntityVO>();
		if(taskInfoList != null){
			if(taskInfoList.size() > 0){
				for (TaskTemplateEntity task : taskInfoList) {
					TaskInfoEntityVO vo  = new TaskInfoEntityVO();
					vo.setId(task.getId());
					vo.setTaskName(task.getName());
					vo.setFrequency(task.getFrequency()+"");
					vo.setFromCity(task.getFromCity());
					vo.setGrabChannel(task.getGrabChannel());
					vo.setFromCityName(task.getFromCityName());
					vo.setToCityName(task.getToCityName());
					vo.setPriority(task.getPriority());
					//
					
					vo.setIsReturn(task.getIsReturn().toString());
					vo.setReturnDateScope(task.getReturnDateScope());
					vo.setGrabsopeBegin(task.getGrabScopeBegin());
					vo.setGrabsopeEnd(task.getGrabScopeEnd());
					//vo.setGrabsope(task.getGrabsope());
					vo.setRemark(task.getRemark());
					vo.setToCity(task.getToCity());
					vo.setValidityFrom(task.getValidityFrom());
					vo.setValidityTo(task.getValidityTo());
					vo.setUserCreateTime(task.getCreateTime());
					vo.setUserName(task.getUserName());
					vo.setGrabChannelId(task.getGrabChannelId());
					if(task.getAssignDayList()!=null){
						List<TaskAssignDayEntityVO> assignDayList =new ArrayList<TaskAssignDayEntityVO>();
						for(TaskAssignDayEntity entity:task.getAssignDayList()){
							TaskAssignDayEntityVO assignVO=new TaskAssignDayEntityVO();
							assignVO.setId(entity.getId());
							assignVO.setAssignFlightDay(entity.getAssignFlightDay());
							assignVO.setAssignRoundDay(entity.getAssignRoundDay());
							assignDayList.add(assignVO);
						}
						vo.setAssignDayList(assignDayList);
					}
					voList.add(vo);
				}
			}
		}
		return voList;
	}

	@Override
	public Page<TaskInfoEntityVO> pageFindaskInfoEntityVOCriteriaList(String grabChannel,
			String fromCity, String toCity, int grabsopeBegin,int grabsopeEnd,Date validityFrom, int pageNum,int pageSize) {
		List<TaskInfoEntityVO> result =new ArrayList<TaskInfoEntityVO>();
		List<Object> conditionVals = new ArrayList<Object>();
		StringBuilder jpql =new StringBuilder("select t from TaskTemplateEntity t where 1=1 ");
		if(StringUtils.isNotEmpty(grabChannel)){
			jpql.append(" and t.grabChannel = ? ");
			conditionVals.add(grabChannel);
		}
		if(StringUtils.isNotEmpty(fromCity)){
			jpql.append(" and t.fromCity = ? ");
			conditionVals.add(fromCity);
		}
		if(StringUtils.isNotEmpty(toCity)){
			jpql.append(" and t.toCity = ? ");
			conditionVals.add(toCity);
		}
		if(grabsopeBegin!=0){
			jpql.append(" and t.grabScopeBegin = ? ");
			conditionVals.add(grabsopeBegin);
		}
		if(grabsopeEnd!=0){
			jpql.append(" and t.grabScopeEnd = ? ");
			conditionVals.add(grabsopeEnd);
		}
		
		if(validityFrom!=null){
			jpql.append("and to_char(t.validityFrom,'yyyy-mm-dd hh24:mi:ss') like ? ");
			SimpleDateFormat sf=
					new SimpleDateFormat("yyyy-MM-dd");
			conditionVals.add(sf.format(validityFrom)+"%");
		}
		
		jpql.append(" order by t.createTime desc  ");
		
		try {
			Page<TaskTemplateEntity> pages =queryChannel1.queryPagedResultByPageNo(jpql.toString(), conditionVals.toArray(), pageNum, pageSize);
			if(pages.getTotalCount() > 0){
				for(TaskTemplateEntity task : pages.getResult()){
					TaskInfoEntityVO vo  = new TaskInfoEntityVO();
					vo.setId(task.getId());
					vo.setTaskName(task.getName());
					vo.setFrequency(task.getFrequency()+"");
					vo.setFromCity(task.getFromCity());
					vo.setGrabChannel(task.getGrabChannel());
					vo.setFromCityName(task.getFromCityName());
					vo.setToCityName(task.getToCityName());
					vo.setPriority(task.getPriority());
					//
					
					vo.setIsReturn(task.getIsReturn().toString());
					vo.setReturnDateScope(task.getReturnDateScope());
					vo.setGrabsopeBegin(task.getGrabScopeBegin());
					vo.setGrabsopeEnd(task.getGrabScopeEnd());
					//vo.setGrabsope(task.getGrabsope());
					vo.setRemark(task.getRemark());
					vo.setToCity(task.getToCity());
					vo.setValidityFrom(task.getValidityFrom());
					vo.setValidityTo(task.getValidityTo());
					vo.setUserCreateTime(task.getCreateTime());
					vo.setUserName(task.getUserName());
					vo.setGrabChannelId(task.getGrabChannelId());
					if(task.getAssignDayList()!=null){
						List<TaskAssignDayEntityVO> assignDayList =new ArrayList<TaskAssignDayEntityVO>();
						for(TaskAssignDayEntity entity:task.getAssignDayList()){
							TaskAssignDayEntityVO assignVO=new TaskAssignDayEntityVO();
							assignVO.setId(entity.getId());
							assignVO.setAssignFlightDay(entity.getAssignFlightDay());
							assignVO.setAssignRoundDay(entity.getAssignRoundDay());
							assignDayList.add(assignVO);
						}
						vo.setAssignDayList(assignDayList);
					}
					result.add(vo);
				}
			}
			
			return new Page<TaskInfoEntityVO>(pages.getCurrentPageNo(), pages.getTotalCount(), pages.getPageSize(), result);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void save(TaskInfoEntityVO vo) throws Exception {
		TaskTemplateEntity taskInfo=new TaskTemplateEntity();
		LogonUserCertificate currentUser = com.fare.taluo.auth.security.ContextLoginUser.getLoginUser();//拿到登录的用户
		PortEntityVO portVO = null;
		if(StringUtils.isNotEmpty(vo.getFromCity())){
			portVO = portApplication.findCityNameByPortCode(vo.getFromCity());
		}
		if(null != portVO && 
				!StringUtils.isEmpty(portVO.getAreaCode()) &&
				!StringUtils.isEmpty(portVO.getAreaName())){
			taskInfo.setAreaName(portVO.getAreaName());
			taskInfo.setAreaCode(portVO.getAreaCode());
		}else{
			throw new Exception("机场区域信息为空");
		}
		taskInfo.setName(vo.getTaskName());
		taskInfo.setGrabChannel(vo.getGrabChannel());
		taskInfo.setFromCity(vo.getFromCity());
		taskInfo.setFromCityName(vo.getFromCityName());
		taskInfo.setToCity(vo.getToCity());
		taskInfo.setToCityName(vo.getToCityName());
		taskInfo.setValidityFrom(vo.getValidityFrom());
		taskInfo.setValidityTo(vo.getValidityTo());
		//从小时转为分钟
		taskInfo.setFrequency(Integer.valueOf(vo.getFrequency()));
		taskInfo.setRemark(vo.getRemark());
		taskInfo.setGrabScopeBegin(vo.getGrabsopeBegin());
		taskInfo.setGrabScopeEnd(vo.getGrabsopeEnd());
		taskInfo.setIsReturn(StringUtils.isNotBlank(vo.getIsReturn()) && NumberUtils.isNumber(vo.getIsReturn()) ? Integer.valueOf(vo.getIsReturn()) : 0);
		taskInfo.setReturnDateScope(vo.getReturnDateScope());
		taskInfo.setStatus(vo.getStatus());
		taskInfo.setNextGrabTime(new Date());
		taskInfo.setPriority(vo.getPriority());
		taskInfo.setGrabChannelId(vo.getGrabChannelId());
		taskInfo.setAttachHbaseKey(vo.getAttachHbaseKey());
		taskInfo.setUserName(currentUser.getUserName());
		taskInfo.setUserId(currentUser.getUserId());
		if(vo.getAssignDayList()!=null){
			Set<TaskAssignDayEntity> assignEntiyList= new HashSet<TaskAssignDayEntity>();
			for(TaskAssignDayEntityVO assignVo :vo.getAssignDayList()){
				TaskAssignDayEntity entity = new TaskAssignDayEntity();
				if(assignVo.getId()!=null && assignVo.getId()!=0)
				entity.setId(assignVo.getId());
				entity.setAssignFlightDay(assignVo.getAssignFlightDay());
				entity.setAssignRoundDay(assignVo.getAssignRoundDay());
				entity.setTaskTemplateEntity(taskInfo);
				assignEntiyList.add(entity);
			}
			taskInfo.setAssignDayList(assignEntiyList);
		}
		if( vo.getId()!=null && vo.getId()>0){taskInfo.setId(vo.getId());}
		//南航的相应处理
		taskInfo.saveOrUpdateTaskInfoEntity();
		
	}
	
	public  boolean isNumeric(String str){  
		   for(int i=str.length();--i>=0;){  
		      int chr=str.charAt(i);  
		      if(chr<48 || chr>57)  
		         return false;  
		   }  
		   return true;  
		}  

}
